package com.skytech.tax.customsdatawarehouse.electronicport.proceedspayment.importpayment.domain.dao;

import com.skytech.tax.customsdatawarehouse.electronicport.proceedspayment.importpayment.domain.entity.ImportPayment;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lianhong
 * @since 2021/11/19
 */
@Repository
public class ImportPaymentDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private final String saveImportPaymentSql = "INSERT INTO e_import_payment " +
            "(entryId, importPayment, storageTime, socialCreditCode, dDate, iEDate)" +
            " VALUES (:entryId, :importPayment, :storageTime, :socialCreditCode, :dDate, :iEDate)";

    public void save(ImportPayment payment) {
        payment.setStorageTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        this.namedParameterJdbcTemplate.update(this.saveImportPaymentSql, new BeanPropertySqlParameterSource(payment));
    }

    private String selectImportPaymentSql = "SELECT entryId, importPayment, storageTime FROM e_import_payment WHERE 1=1";

    public ImportPayment findByEntryId(String entryId) {
        StringBuilder sql = new StringBuilder(this.selectImportPaymentSql);
        List<Object> params = new ArrayList<>();
        if (StringUtils.isNotEmpty(entryId)) {
            sql.append(" AND entryId = ? ");
            params.add(entryId);
        }
        try {
            return namedParameterJdbcTemplate.getJdbcOperations()
                    .queryForObject(sql.toString(), params.toArray(), new BeanPropertyRowMapper<>(ImportPayment.class));
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private String deleteImportPaymentSql = "DELETE FROM e_import_payment WHERE entryId = ?";

    public void delete(String entryId) {
        this.namedParameterJdbcTemplate.getJdbcOperations().update(this.deleteImportPaymentSql, entryId);
    }
}
